import 'dart:io';

import 'package:bwt_ad_flutter/ad/BwtNativeExpressAd.dart';
import 'package:bwt_ad_flutter_example/controller/SimpleGetxController.dart';
import 'package:bwt_ad_flutter_example/util/ListGridBuilderUtil.dart';
import 'package:bwt_ad_flutter_example/util/Log.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:bwt_ad_flutter/ad/loader/BwtNativeExpressAdLoader.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../model/NativeExpressItem.dart';
import '../util/DisplayUtil.dart';

class NativeExpressAdListDataPage extends StatefulWidget {
  const NativeExpressAdListDataPage({super.key});

  @override
  State<StatefulWidget> createState() => _NativeExpressAdPageState();
}

class _NativeExpressAdPageState extends State<NativeExpressAdListDataPage> {
  final BwtNativeExpressAdLoader _nativeExpressAdLoader =
      BwtNativeExpressAdLoader();
  final SimpleGetxController<List<NativeExpressItem>> _dataList =
      SimpleGetxController();
  final EasyRefreshController _refreshController = EasyRefreshController(
    controlFinishRefresh: true,
    controlFinishLoad: true,
  );

  int _page = 0;
  bool _isRefresh = true;
  final int _pageSize = 20;
  List<NativeExpressItem>? _tempDataList;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("信息流模板广告-列表场景"),
      ),
      body: Container(
        color: Colors.white,
        height: double.infinity,
        child: EasyRefresh(
          controller: _refreshController,
          header: const ClassicHeader(),
          footer: const ClassicFooter(),
          canRefreshAfterNoMore: true,
          resetAfterRefresh: true,
          onRefresh: () => _loadData(true),
          onLoad: () => _loadData(false),
          child: ListGridBuilderUtil.listBuilder<NativeExpressItem>(
            shrinkWrap: true,
            dataController: _dataList,
            childItemBuilder: (item, context) {
              var expressAd = item.item.bwtNativeExpressAd?.expressAd;

              if (expressAd == null) {
                // 正常业务数据
                return _buildNormalItem(item.item);
              }

              // 广告数据
              return expressAd;
            },
          ),
        ),
      ),
    );
  }

  /// 构建普通数据的Item
  Widget _buildNormalItem(NativeExpressItem item) {
    return Container(
      width: double.infinity,
      height: 48,
      padding: const EdgeInsets.symmetric(horizontal: 16),
      alignment: Alignment.centerLeft,
      child: Text(
        item.title ?? '',
        style: const TextStyle(
          fontSize: 16,
          color: Colors.blue,
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();

    // 设置广告加载成功监听
    _nativeExpressAdLoader.onAdLoad = (bwtAd) {
      _loadFinish(bwtAd);
      Log.d('信息流模板广告加载成功...');
    };

    // 设置广告加载失败监听
    _nativeExpressAdLoader.onAdFailed = (msg) {
      _loadFinish(null);
      Log.d('信息流模板广告加载失败, $msg');
      Fluttertoast.showToast(msg: "广告加载失败了～");
    };

    // 设置广告展示监听
    _nativeExpressAdLoader.onAdExpose = (bwtAd) {
      Log.d('信息流模板广告展示成功...');
    };

    // 设置广告被点击监听
    _nativeExpressAdLoader.onAdClick = (bwtAd) {
      Log.d('信息流模板广告被点击...');
    };

    // 设置广告被关闭监听
    _nativeExpressAdLoader.onAdClose = (bwtAd) {
      Log.d('信息流模板广告被关闭...');
    };

    // 自动触发下拉刷新
    Fluttertoast.showToast(msg: "正在加载...");
    _loadData(true);
  }

  @override
  void dispose() {
    /// 释放广告
    _nativeExpressAdLoader.release();
    super.dispose();
  }

  /// 加载数据
  void _loadData(bool isRefresh) {
    _isRefresh = isRefresh;
    if (isRefresh) _page = 0;

    // 模拟加载数据
    int start = _page * _pageSize;
    _tempDataList = [];
    for (var i = 0; i < _pageSize; i++) {
      _tempDataList?.add(NativeExpressItem('Item is: ${start + i}', null));
    }

    // 加载信息流模板广告
    _nativeExpressAdLoader.loadAd(
      // 广告位ID，不同端的广告位ID可能不一致，需替换成自己相应端的广告位ID
      posId: Platform.isAndroid ? '64967792' : '87522319',
      // 广告宽度
      adWidth: DisplayUtil.screenWidth,
    );
  }

  /// 业务数据和广告数据均加载结束
  void _loadFinish(BwtNativeExpressAd? bwtAd) {
    var itemList = _dataList.data ?? [];

    // 更新下拉刷新组件
    if (_isRefresh) {
      itemList = [];
      _refreshController.finishRefresh();
      _refreshController.resetFooter();
    } else {
      _refreshController.finishLoad();
    }

    var tempList = _tempDataList ?? [];
    if (bwtAd != null) {
      // 如果广告数据不为空，把广告放在想要的位置
      if (tempList.length > 5) {
        tempList.insert(5, NativeExpressItem(null, bwtAd));
      } else {
        tempList.add(NativeExpressItem(null, bwtAd));
      }
    }

    // 将数据添加到列表中
    itemList.addAll(tempList);

    _page++;
    _dataList.data = itemList;
  }
}
